package com.zzxx.userManagement.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter({"/userInfo/*", "*.jsp"})
public class PermissionFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        // 判断是不是要过滤的资源 Servlet + jsp 除了login.jsp
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String uri = req.getRequestURI();
        if (!uri.endsWith("login.jsp")) {
            // 要求权限判断是已登录状态
            Object user = req.getSession().getAttribute("user");
            if (user == null) { // 没登录, 不能进入
                resp.sendRedirect(req.getContextPath() + "/login.jsp");
            } else {
                chain.doFilter(request, response);
            }
        } else {
            // index.jsp login.jsp
            chain.doFilter(request, response);
        }
    }
}
